<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { login, register, getCode } from '@/api/user'
import { useUserStore } from '@/stores/index'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loginFormRef = ref(null)
const registerFormRef = ref(null)
const isSubmitting = ref(false)

const isRegisterMode = ref(false)

const countdown = ref(60)
const isCountingDown = ref(false)
const countdownText = ref('获取验证码')

const loginForm = reactive({
  phone: '',
  password: '',
  code: '',
  loginType: 'password', // 'password' or 'code'
  remember: false
})

const registerForm = reactive({
  phone: '',
  password: '',
  code: '',
  confirmPassword: ''
})

const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    countdownText.value = `${countdown.value}s`
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
      countdownText.value = '获取验证码'
    }
  }, 1000)
}

const onSendCode = async () => {
  const phoneNumber = isRegisterMode.value
    ? registerForm.phone
    : loginForm.phone

  if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
    ElMessage.error('请输入正确的手机号')
    return
  }

  try {
    const res = await getCode(phoneNumber)
    if (res.code === 1) {
      ElMessage.success('验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('验证码发送失败')
    console.error('发送验证码错误:', error)
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value || isSubmitting.value) return

  try {
    isSubmitting.value = true
    await loginFormRef.value.validate()

    const loginData = {
      phone: loginForm.phone,
      ...(loginForm.loginType === 'password'
        ? { password: loginForm.password }
        : { code: loginForm.code })
    }

    const res = await login(loginData)
    if (res.code === 1) {
      userStore.setToken(res.msg)
      console.log(userStore.token)
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(res.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败')
  } finally {
    isSubmitting.value = false
  }
}

const handleRegister = async () => {
  if (!registerFormRef.value || isSubmitting.value) return

  try {
    isSubmitting.value = true
    await registerFormRef.value.validate()

    const res = await register(registerForm)
    if (res.code === 1) {
      userStore.setToken(res.msg)
      ElMessage.success('注册成功')
      await router.replace(route.query.redirect || '/')
    } else {
      ElMessage.error(res.msg || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error(error.message || '注册失败')
  } finally {
    isSubmitting.value = false
  }
}

const toggleLoginMode = () => {
  loginForm.loginType = loginForm.loginType === 'password' ? 'code' : 'password'
  loginFormRef.value?.clearValidate()
}

const resetForms = () => {
  if (loginFormRef.value) loginFormRef.value.resetFields()
  if (registerFormRef.value) registerFormRef.value.resetFields()
  isCountingDown.value = false
  countdown.value = 60
  countdownText.value = '获取验证码'
}

const switchMode = () => {
  isRegisterMode.value = !isRegisterMode.value
  resetForms()
}

const handleForgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}
</script>

<template>
  <div class="auth-container">
    <el-card class="auth-card" :body-style="{ padding: '0px' }">
      <div class="login-section">
        <div class="form-content">
          <h2>小麦管理系统登录</h2>
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-position="top"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="手机号"
                prefix-icon="User"
              />
            </el-form-item>

            <template v-if="loginForm.loginType === 'password'">
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="密码"
                  prefix-icon="Lock"
                  show-password
                />
              </el-form-item>
              <div class="remember-forgot">
                <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                <el-button link type="primary" @click="handleForgotPassword"
                  >忘记密码?</el-button
                >
              </div>
            </template>

            <template v-else>
              <el-form-item prop="code">
                <el-input
                  v-model="loginForm.code"
                  placeholder="验证码"
                  prefix-icon="Message"
                >
                  <template #append>
                    <el-button :disabled="isCountingDown" @click="onSendCode">
                      {{ countdownText }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </template>

            <el-button
              link
              @click="toggleLoginMode"
              style="margin-bottom: 20px"
            >
              切换到{{
                loginForm.loginType === 'password' ? '验证码' : '密码'
              }}登录
            </el-button>

            <el-button
              type="primary"
              class="submit-btn"
              @click="handleLogin"
              :loading="isSubmitting"
            >
              登录
            </el-button>
          </el-form>
        </div>
      </div>

      <div class="register-section">
        <div class="form-content">
          <h2>注册新账号</h2>
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-position="top"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="手机号"
                prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="code">
              <el-input
                v-model="registerForm.code"
                placeholder="验证码"
                prefix-icon="Message"
              >
                <template #append>
                  <el-button :disabled="isCountingDown" @click="onSendCode">
                    {{ countdownText }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-button
              type="primary"
              class="submit-btn"
              @click="handleRegister"
              :loading="isSubmitting"
            >
              注册
            </el-button>
          </el-form>
        </div>
      </div>

      <div class="switch-panel" :class="{ 'move-to-right': isRegisterMode }">
        <div class="switch-content">
          <h3>{{ isRegisterMode ? '已有账号?' : '没有账号?' }}</h3>
          <p>
            {{ isRegisterMode ? '使用已有账号登录' : '注册新账号开始使用' }}
          </p>
          <el-button class="switch-btn" @click="switchMode">
            {{ isRegisterMode ? '去登录' : '去注册' }}
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #fad0c4 0%, #ff9a9e 100%);
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
}

.auth-card {
  width: 900px;
  height: 600px;
  position: relative;
  overflow: hidden;
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-section,
.register-section {
  position: absolute;
  width: 50%;
  height: 100%;
  transition: transform 0.6s ease-in-out;
}

.login-section {
  left: 0;
  z-index: 1;
}

.register-section {
  right: 0;
  z-index: 1;
}

.form-content {
  width: 100%;
  height: 100%;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.form-content h2 {
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
}

.switch-panel {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform 0.6s ease-in-out;
  background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
  z-index: 100;
}

.move-to-right {
  transform: translateX(-100%);
}

.switch-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  text-align: center;
  color: #fff;
}

.switch-content h3 {
  font-size: 24px;
  margin-bottom: 10px;
}

.switch-content p {
  margin-bottom: 20px;
  opacity: 0.8;
}

.switch-btn {
  background: transparent;
  border: 2px solid #fff;
  color: #fff;
  padding: 10px 30px;
  border-radius: 20px;
  font-weight: bold;
}

.switch-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border-radius: 25px;
}

:deep(.el-form) {
  width: 100%;
  max-width: 320px;
}

:deep(.el-input__wrapper) {
  border-radius: 25px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-button) {
  border-radius: 20px;
}

:deep(.el-checkbox__inner) {
  border-radius: 4px;
}

:deep(.el-card) {
  border: none;
  background-color: rgba(255, 255, 255, 0.95);
}

@media (max-width: 968px) {
  .auth-card {
    width: 90%;
    max-width: 700px;
  }
}

@media (max-width: 768px) {
  .auth-container {
    padding: 40px 20px;
  }

  .auth-card {
    width: 95%;
    height: auto;
    min-height: 600px;
    margin: 20px 0;
  }

  .login-section,
  .register-section {
    position: relative;
    width: 100%;
    height: auto;
    min-height: 500px;
  }

  .switch-panel {
    display: none;
  }

  .form-content {
    padding: 20px;
  }

  .form-content h2 {
    font-size: 20px;
    margin-bottom: 20px;
  }

  :deep(.el-form) {
    width: 90%;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-content {
  animation: fadeIn 0.5s ease-out;
}

.text-center {
  text-align: center;
}

.w-full {
  width: 100%;
}

.submit-btn {
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.submit-btn:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.submit-btn:active {
  transform: translateY(0);
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}

.switch-btn {
  transition: all 0.3s ease;
}

.switch-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
}

:deep(.el-input-group__append .el-button) {
  border-radius: 0 20px 20px 0;
  padding: 8px 15px;
}

.remember-forgot .el-checkbox {
  margin-right: 0;
}

.auth-card {
  transition: transform 0.3s ease;
}

.auth-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.switch-panel {
  transition:
    transform 0.6s ease-in-out,
    box-shadow 0.3s ease;
}

.switch-panel:hover {
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

:deep(.el-button.is-loading) {
  opacity: 0.8;
  cursor: wait;
}

:deep(.el-button--link) {
  padding: 0;
  height: auto;
  font-weight: normal;
}

:deep(.el-button--link:hover) {
  text-decoration: underline;
}
</style>
